import '../../../services/messageUtil.dart';

import '../../../models/group_model.dart';
import '../../../models/project_model.dart';

import '../../../services/userServices.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../services/httpsClient.dart';

class HomeController extends GetxController {
  bool isLoading = true; //请求防抖控制
  HttpsClient httpsClient = HttpsClient();
  //左侧分组数据
  RxList<GroupItemModel?> leftGroupList = <GroupItemModel?>[].obs;
  //当前选中的分组信息
  RxInt selectIndex = 0.obs;
  RxMap groupInfo = {'name': '', 'desc': ''}.obs;
  //新增分组信息
  RxString createGroupName = ''.obs;
  RxString createGroupDesc = ''.obs;
  final TextEditingController editGroupNameController = TextEditingController();
  final TextEditingController editGroupDescController = TextEditingController();
  //新增项目信息
  RxString createProjectName = ''.obs;
  RxInt selectedValue = 0.obs;
  RxString selectedName = ''.obs;
  //右侧项目数据
  RxList<ProjectItemModel?> rightProjectList = <ProjectItemModel?>[].obs;
  //右侧项目页选中tab数据
  RxInt currentTabIndex = 1.obs;
  List tabsList = [
    {"id": 1, "title": "项目列表"},
    // {"id": 2, "title": "成员列表"},
    // {"id": 3, "title": "分组动态"},
    {"id": 4, "title": "分组设置"},
  ];
  @override
  void onInit() {
    super.onInit();
    getLeftGroupData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  //获取分组信息
  getLeftGroupData() async {
    var response = await httpsClient.get("v1/group/list");
    if (response != null) {
      var group = GroupModel.fromJson(response.data);
      if (group.data!.isNotEmpty) {
        leftGroupList.value = group.data!;
        //当前选中分组信息
        groupInfo['name'] = leftGroupList[selectIndex.value]!.groupName!;
        groupInfo['desc'] = leftGroupList[selectIndex.value]!.groupDesc!;
        //新增项目时选中的分组信息
        selectedValue.value = leftGroupList[selectIndex.value]!.id!;
        selectedName.value = leftGroupList[selectIndex.value]!.groupName!;
        //请求右侧项目数据
        getRightProjectData(leftGroupList[selectIndex.value]!.id!);
      } else {
        leftGroupList.value = [];
        groupInfo['name'] = "没有分组";
        groupInfo['desc'] = "没有分组简介";
      }

      update();
    }
  }

  //请求右侧项目数据
  getRightProjectData(int groupId) async {
    var response = await httpsClient.get(
      "v1/project/list",
      params: {"group_id": groupId},
    );
    if (response != null) {
      var project = ProjectModel.fromJson(response.data);
      if (project.data!.isNotEmpty) {
        rightProjectList.value = project.data!;
      } else {
        rightProjectList.value = [];
      }
      update();
    }
  }

  //点击左侧分组选中
  void changeIndex(index, groupId) {
    selectIndex.value = index;
    selectedValue.value = groupId;

    groupInfo['name'] = leftGroupList[index]!.groupName!;
    groupInfo['desc'] = leftGroupList[index]!.groupDesc!;
    //编辑分组时回显信息
    editGroupNameController.text = leftGroupList[index]!.groupName!;
    editGroupDescController.text = leftGroupList[index]!.groupDesc!;

    //请求右侧项目数据
    getRightProjectData(groupId);

    update();
  }

  //改变顶部tab切换
  void changeSelectedTabsIndex(index) {
    if (index == 4) {
      //编辑分组
      editGroupNameController.text = groupInfo['name'];
      editGroupDescController.text = groupInfo['desc'];
    }
    currentTabIndex.value = index;
    update();
  }

  // 提交新增分组表单
  void submitForm() async {
    if (isLoading) {
      isLoading = false;

      var response = await httpsClient.post(
        "v1/group/create",
        data: {
          "group_name": createGroupName.value,
          "group_desc": createGroupDesc.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求
          getLeftGroupData();
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 提交编辑分组表单
  void submitEditGroupForm() async {
    if (isLoading) {
      isLoading = false;

      var response = await httpsClient.post(
        "v1/group/edit",
        data: {
          "group_id": leftGroupList[selectIndex.value]!.id!,
          "group_name": editGroupNameController.text,
          "group_desc": editGroupDescController.text,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "更新成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );

          //重新请求
          getLeftGroupData();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 提交删除分组表单
  void submitDelGroupForm() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/group/del",
        data: {"group_id": leftGroupList[selectIndex.value]!.id!},
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "删除成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );

          //重新请求
          getLeftGroupData();
          selectIndex.value = 0;
          currentTabIndex.value = 1;
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 新增项目更新选中值
  void onChanged(int? value) {
    if (value != null) {
      selectedValue.value = value;
      final selected = leftGroupList.firstWhere((item) => item?.id == value);
      selectedName.value = selected!.groupName!;
      update();
    }
  }

  // 提交新增项目表单
  void submitProjectForm() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/project/create",
        data: {
          "project_name": createProjectName.value,
          "group_id": selectedValue.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求右侧项目数据
          getRightProjectData(leftGroupList[selectIndex.value]!.id!);
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }
}
